<script lang="ts" setup>
import type { SmsSubjectItemType, SmsSubjectValueType } from '@/apis/sms-setting'
import { getUserCenterSmsTopicPropertiesConfig, getUserCenterSmsTopicPropertiesConfigInitData, updateUserCenterSmsTopicPropertiesConfig } from '@/apis/sms-setting'
import useRequest from '@/hooks/useRequest'
import { message } from 'ant-design-vue'

const formRef = ref()
const loading = ref()

const formItemList = ref<SmsSubjectItemType[]>([])
const formState = reactive<any>({})

async function onSave() {
  try {
    await formRef.value.validate()
    loading.value = true
    await updateUserCenterSmsTopicPropertiesConfig(formState)
    message.success('更新成功')
  }
  catch (error) {
    console.log(error)
  }
  finally {
    loading.value = false
  }
}

const { run, data } = useRequest<any>(getUserCenterSmsTopicPropertiesConfig)
const { run: getInitData, data: initData, loading: initDataLoading } = useRequest<SmsSubjectValueType>(getUserCenterSmsTopicPropertiesConfigInitData)

onMounted(async () => {
  try {
    await Promise.all([run(), getInitData()])
    formItemList.value = data.value?.elements.map((item: SmsSubjectItemType) => {
      formState[item.key as string] = (initData.value as any)[item.key as string]
      return {
        ...item,
      }
    })
  }
  catch (error) {
    console.log(error)
  }
})
</script>

<template>
  <div class="w-50% margin-auto mt-50px">
    <a-spin :spinning="initDataLoading">
      <a-form
        ref="formRef"
        size="large"
        :model="formState"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-item
          v-for="item in formItemList"
          :key="item.key"
          :label="item.label"
          :name="item.key"
          :rules="[{ required: true, message: `请输入${item.label}` }]"
        >
          <a-input v-model:value="formState[item.key as string]" :placeholder="item.placeholder || `请输入${item.label}`" />
        </a-form-item>

        <a-form-item class="text-right" :wrapper-col="{ offset: 8, span: 14 }">
          <a-button :loading="loading" type="primary" @click="onSave">
            保存
          </a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>
